package com.example.customview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Switch;

import androidx.annotation.Nullable;

/**
 * 描述
 *
 * @创建时间 2023/8/21 18:31
 */
public class ShapeView extends View {
    Paint mPaint;
    Shape mCurrentShape = Shape.Square;
    public ShapeView(Context context) {
        this(context,null);
    }

    public ShapeView(Context context, @Nullable AttributeSet attrs) {
        this(context,attrs,0);
    }

    public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        //抗锯齿
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 宽度高度不一致 取最小值，确保是个正方形
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width>height?height:width,width>height?height:width);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        switch (mCurrentShape){
            case Square:
                //画三角形
                mPaint.setColor(Color.BLUE);
                Path path = new Path();
                path.moveTo(getWidth()/2,0);
                path.lineTo(0,getHeight());
                path.lineTo(getWidth(),getHeight());
                path.close();    //路劲闭合
                canvas.drawPath(path,mPaint);
                break;
            case Circle:
                int center = getWidth()/2;
                mPaint.setColor(Color.RED);
                canvas.drawCircle(center,center,center,mPaint);
                break;
            case Triangle:
                //画正方形
                mPaint.setColor(Color.GREEN);
                canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
                break;
            default:
                break;
        }
    }

    public void exchange() {
        switch (mCurrentShape) {
            case Circle:
                mCurrentShape = Shape.Square;
                break;
            case Square:
                mCurrentShape = Shape.Triangle;
                break;
            case Triangle:
                // 画三角  Path 画路线
                mCurrentShape = Shape.Circle;
                break;
        }
        invalidate();
    }

    public enum Shape{
        Circle,Square,Triangle
    }
}
